package com.kgc.dubbo.component;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 日志记录的工具类
 */
@Component
@Data
@ConfigurationProperties(prefix = "spring.kafka")
public class KafkaUtil {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    private String moduleName;

    private String key="qg";

     class LogType{
        public static final String INFO="info";
        public static final String ERROR="error";
    }

    /**
     * 发送普通的日志信息到kafka
     * @param message 需要发送的信息
     */

    public void commonLog(String message){
        kafkaTemplate.send(moduleName+"-"+ LogType.INFO,key,message);
    }

    /**
     * 发送错误的日志信息到kafka
     * @param e 异常对象
     */

    public void errorLog(Exception e){
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        kafkaTemplate.send(moduleName+"-"+ LogType.ERROR,key,writer.toString());
    }
}
